package com.cloudpark.auth;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.cloudpark.common.util.Constants;
import com.cloudpark.model.entity.AdminUser;
import com.cloudpark.service.UserService;

public class AuthFilter extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        System.out.println("************doGetAuthenticationInfo************");
        // 获取用户
        String account = token.getUsername();
        AdminUser user = userService.findByAccount(account);
        setSession(Constants.SESSION_USER, user);
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), getName());
        return sai;
    }

    /**
     * 将一些数据放到ShiroSession�?以便于其它地方使�?
     * 
     * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取�?
     */
    private void setSession(Object key, Object value) {
        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            Session session = subject.getSession();
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }
}
